import axios, { AxiosRequestConfig } from 'axios'
import _ from 'lodash'

import { IListItem } from './interface'
import { reqToList } from './utils'
import './__mock__'

/** 获取运单信息列表 */
export const apiGetListWaybillInfo = (
  req: { waybillNos?: string[]; fbaIds?: string[] },
  signal?: AxiosRequestConfig['signal'],
): Promise<IListItem[]> => {
  return axios
    .post(
      '/tmsapi/track_waybill/listWaybillInfo',
      { waybillNos: req.waybillNos || [], fbaIds: req.fbaIds || [] },
      { $extra: 'noAuth', signal },
    )
    .then(res => {
      const list: IListItem[] = res.$data || []
      const notFoundList: IListItem[] = []
      reqToList(req).forEach(({ type, value }) => {
        const diffWaybillNo = type === 'waybillNos' ? value : '$empty'
        const diffFbaId = type === 'fbaIds' ? value : '$empty'
        if (list.every(d => d.waybillNo !== diffWaybillNo && d.fbaId !== diffFbaId)) {
          notFoundList.push({
            $key: '',
            logisticsStatusEn: '',
            waybillNo: diffWaybillNo === '$empty' ? '' : diffWaybillNo,
            fbaId: diffFbaId === '$empty' ? null : diffFbaId,
            age: null,
            deliveryDate: null,
            latestRoute: null,
            markFlag: null,
            $NotFound: true,
          })
        }
      })
      return [...list, ...notFoundList].map(d => ({ ...d, $key: _.uniqueId() }))
    })
}
